<template>
  <div class="wrap">
    <v-sheet class="oper">
      <v-btn-toggle
        dense
        class="rounded-0"
        @change="changeBtn"
        v-model="whichBtn"
      >
        <v-btn>
          <v-icon>keyboard_return</v-icon>
        </v-btn>

        <v-btn id="expendBtn">
          <v-icon>{{ expendIcon }}</v-icon>
        </v-btn>

        <v-btn>
          <v-icon>{{ penIcon }}</v-icon>
        </v-btn>

        <v-btn>
          <v-icon>reply</v-icon>
        </v-btn>

        <v-btn>
          <v-icon>chevron_left</v-icon>
        </v-btn>

        <v-btn>
          <v-icon>chevron_right</v-icon>
        </v-btn>

        <v-btn>{{ nowPage }}</v-btn>
      </v-btn-toggle>
    </v-sheet>

    <div class="canv-wrap" id="canvWrap" ref="canvWrap">
      <canvas id="canv" ref="canv"></canvas>
    </div>
  </div>
</template>

<script>
import { getOnePPT } from '@/api/ppt'
import { fabric } from 'fabric'
import $ from 'jquery'
export default {
  name: 'movie',
  data() {
    return {
      tempAdd: [],
      canvIndex: 0,
      whichBtn: null,
      expendIcon: 'zoom_out_map',
      penIcon: 'near_me',
      id: 0,
      ppt: {
        content: []
      },
      canv: null,
      scale: 16 / 9, // 画布宽高比例
      zoom: 1, // 画布当前缩放
      cw: 1920, // 画布实际宽
      ch: 1080, // 画布实际高
      ow: 1920, // 画布比例宽
      oh: 1080, // 画布比例、高
      gx: 0, // 画布的x边距
      gy: 0 // 画布的y边距
    }
  },
  computed: {
    nowPage() {
      return `${this.canvIndex + 1}/${this.ppt.content.length}`
    }
  },
  mounted() {
    this.id = this.$route.params.id
    this.$nextTick(() => {
      this.initCanv()
      this.getPPT()
      this.mountEvent()
    })
  },
  beforeRouteLeave(to, from, next) {
    // 关闭弹窗
    if (this.webFrame) {
      this.webFrame.close()
    }
    next()
  },
  destroyed() {
    // 关闭弹窗
    if (this.webFrame) {
      this.webFrame.close()
    }
  },
  methods: {
    //全屏
    fullScreen() {
      const el = document.documentElement
      const rfs =
        el.requestFullScreen ||
        el.webkitRequestFullScreen ||
        el.mozRequestFullScreen ||
        el.msRequestFullScreen

      if (rfs) {
        rfs.call(el)
      }
    },
    //退出全屏
    exitScreen() {
      const el = document
      const cfs =
        el.cancelFullScreen ||
        el.webkitCancelFullScreen ||
        el.mozCancelFullScreen ||
        el.exitFullScreen

      if (cfs) {
        cfs.call(el)
      }
    },
    changeBtn() {
      if (this.whichBtn === 0) {
        this.$router.go(-1)
      } else if (this.whichBtn === 1) {
        if (this.expendIcon === 'zoom_out_map') {
          this.fullScreen()
          this.expendIcon = 'zoom_in_map'
        } else {
          this.exitScreen()
          this.expendIcon = 'zoom_out_map'
        }
      } else if (this.whichBtn === 2) {
        if (this.penIcon === 'edit') {
          this.canv.isDrawingMode = false
          this.penIcon = 'near_me'
        } else {
          this.canv.isDrawingMode = true
          this.penIcon = 'edit'
        }
      } else if (this.whichBtn === 3) {
        if (this.tempAdd[this.canvIndex] >= 1) {
          const itemList = this.canv.getObjects()
          const item = itemList[itemList.length - 1]
          this.canv.remove(item)
          this.tempAdd[this.canvIndex]--
          this.ppt.content[this.canvIndex] = this.canv.toJSON(['webUrl', 'id'])
        }
      } else if (this.whichBtn === 4) {
        this.prevPage()
      } else if (this.whichBtn === 5) {
        this.nextPage()
      }
      this.$nextTick(() => {
        this.whichBtn = null
      })
    },
    openWebFrame(item) {
      return () => {
        if (this.webFrame && !this.webFrame.closed) {
          this.webFrame.focus()
          return
        }
        const width = 1400
        const height = 780
        const left = (window.outerWidth - width) / 2
        const top = (window.outerHeight - height) / 2
        this.webFrame = window.open(
          item.webUrl,
          'webFrame',
          `left=${left}, top=${top}, width=${width}, height=${height}`
        )
        this.webFrame.focus()
      }
    },
    renderCanv() {
      this.canv.loadFromJSON(this.ppt.content[this.canvIndex], () => {
        this.canv.getObjects().forEach(item => {
          if (item.webUrl) {
            item.on('mousedown', this.openWebFrame(item))
          }
        })
      })
    },
    nextPage() {
      if (this.canvIndex <= this.ppt.content.length - 2) {
        this.canvIndex++
        this.renderCanv()
      }
    },
    prevPage() {
      if (this.canvIndex >= 1) {
        this.canvIndex--
        this.renderCanv()
      }
    },
    getPPT() {
      this.$layer.show()
      getOnePPT({ id: this.id })
        .then((res) => {
          this.ppt = res.data.data
          this.ppt.content = JSON.parse(this.ppt.content)
          this.ppt.content.forEach(item => {
            item.objects.forEach(obj =>  {
              obj.selectable = false
              if (obj.webUrl) {
                obj.hoverCursor = 'pointer'
              } else {
                obj.hoverCursor = 'default'
              }
            })
          })
          this.renderCanv()
        })
        .catch(() => {})
        .complete(() => {
          this.$layer.hide()
        })
    },
    initCanv() {
      // 初始化临时画布
      this.canv = new fabric.Canvas('canv', {
        backgroundColor: 'white',
        width: this.ow,
        height: this.oh,
        selection: false,
        // skipTargetFind: true
      })
      this.getSize()
      this.resetSize()
      this.canv.isDrawingMode = false
      this.canv.on('path:created', () => {
        if (this.canv.isDrawingMode) {
          if (!this.tempAdd[this.canvIndex]) {
            this.tempAdd[this.canvIndex] = 1
          } else {
            this.tempAdd[this.canvIndex]++
          }
          this.ppt.content[this.canvIndex] = this.canv.toJSON(['webUrl', 'id'])
        }
      })
    },
    // 页面大小改变时获取画布应变为的大小
    getSize() {
      const tw = $('#canvWrap').width()
      const th = $('#canvWrap').height()
      const scale = tw / th
      // 非常长
      if (scale >= this.scale) {
        this.ch = th - this.gy * 2
        this.cw = this.ch * this.scale
      } else {
        this.cw = tw - this.gx * 2
        this.ch = this.cw / this.scale
      }
      this.zoom = this.cw / this.ow
    },
    // 重置画布大小
    resetSize() {
      this.canv.setZoom(this.zoom)
      this.canv.setWidth(this.cw)
      this.canv.setHeight(this.ch)
    },
    mountEvent() {
      $(window).on('beforeunload', () => {
        if (!/.*\/movie\/.*/.test(window.location.href)) {
          return
        }
        console.log('ss')
        if (this.webFrame) {
          this.webFrame.close()
        }
      })
      $(window).on('resize', () => {
        if (!/.*\/movie\/.*/.test(window.location.href)) {
          return
        }
        // 获取全屏状态
        if ($(window).height() === window.screen.height) {
          this.expendIcon = 'zoom_in_map'
        } else {
          this.expendIcon = 'zoom_out_map'
        }
        setTimeout(() => {
          this.getSize()
          this.resetSize()
        }, 300)
      })
      $(document).on('keydown', (e) => {
        if (!/.*\/movie\/.*/.test(window.location.href)) {
          return
        }
        // 回车和右键
        if (e.keyCode === 13 || e.keyCode === 39) {
          this.nextPage()
        }
        // 左键
        if (e.keyCode === 37) {
          this.prevPage()
        }
      })
    }
  }
}
</script>

<style scoped>
.wrap {
  overflow: hidden;
  width: 100%;
  height: 100vh;
}
.canv-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: black;
}
.oper {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 10000;
  opacity: 0.6;
  transition: opacity 0.2s;
}
.oper:hover {
  opacity: 1;
}
</style>
